package com.example.classload;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author xia
 * @className Test
 * @date 2022/9/30 13:58
 */
public class Test {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        // 引导类加载器。 rt.jar chatset.jar
        // 扩展类加载器。 lib/ext
        // 应用类加载器。
        System.out.println(String.class.getClassLoader());

        System.out.println(Test.class.getClassLoader());
        System.out.println(Test.class.getClassLoader().getParent());
        System.out.println(Test.class.getClassLoader().getParent().getParent());
        System.out.println("--------------------");
        System.out.println(Test.class.getClassLoader().loadClass("java.lang.String"));
        // 双亲委派机制
        // 1.安全性。避免核心类库被篡改
        // 2.避免类的重复加载
        MyClassLoadTest myClassLoadTest = new MyClassLoadTest("/Users/xiatie/Documents/testClassLoad/com/example/classload");
        Class<?> aClass = myClassLoadTest.loadClass("com.example.classload.Test");

        Object newInstance = aClass.newInstance();

        Method printTest = aClass.getDeclaredMethod("printTest", null);

        printTest.invoke(newInstance, null);

        System.out.println(aClass.getClassLoader().getClass().getName());
    }

    public void printTest() {
        System.out.println("自定义类加载器");
    }
}
